package com.tanhua.dubbo.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.dubbo.api.db.ReportApi;
import com.tanhua.dubbo.api.mapper.ReportMapper;
import com.tanhua.model.db.Report;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lamy
 * @version 1.0
 * @ClassName: ReportApi
 * @date 2021-12-27 17:19:36
 */
//结果报告表实现类
@DubboService
public class ReportApiImpl implements ReportApi {
    @Autowired
    private ReportMapper reportMapper;

    //插入report记录
    @Override
    public String insert(Report report) {
        QueryWrapper<Report> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("questionnaire_id",report.getQuestionnaireId()).eq("user_id",report.getUserId());
        Report finishReport = reportMapper.selectOne(queryWrapper);
        //判断该报告是否为空
        if (finishReport!=null){
            //不为空则修改报告
            report.setId(finishReport.getId());
            reportMapper.update(report,queryWrapper);
        }else {
            //为空则新增报告
            reportMapper.insert(report);
        }

        return report.getId().toString();
    }

    //根据id查询report
    @Override
    public Report findReport(Long id) {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",id);
        return reportMapper.selectOne(queryWrapper);
    }

    /**
     * 查找相似用户
     * @param maxScore
     * @param minScore
     * @param report
     * @return
     */
    @Override
    public List<Long> findUsers(Integer maxScore, Integer minScore, Report report) {
        QueryWrapper<Report> queryWrapper = new QueryWrapper<>();
        //相似用户排除自己，且分数区间在5以内，且都做了同一份报告的数据
        queryWrapper.ge("score",minScore).le("score",maxScore).notIn("user_id",report.getUserId()).eq("questionnaire_id", report.getQuestionnaireId());
        List<Report> reports = reportMapper.selectList(queryWrapper);
        List<Long> userIds = reports.stream().map(Report::getUserId).collect(Collectors.toList());
        Collections.shuffle(userIds);
        if (userIds.size()>10){
            userIds = userIds.subList(0, 10);
        }
        return userIds;
    }

    /**
     * 获取报告
     * @param questionnaireId
     * @param userId
     * @return
     */
    @Override
    public Report findOne(Long questionnaireId, Long userId) {
        QueryWrapper<Report> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("questionnaire_id",questionnaireId).eq("user_id",userId);
        Report report = reportMapper.selectOne(queryWrapper);
        return report;
    }
}
